/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。
 * 
 * 欢迎到知启蒙网站（https://www.zhiqim.com）购买正版软件，知启蒙还提供许多开源框架和软件。
 * 
 * 1、本软件产品所有源代码受《中华人民共和国著作权法》和其他有关法律、法规的保护，其所有知识产权归湖南知启蒙科技有限公司所有；
 * 2、禁止复制和修改。不得复制修改、翻译或改编本软件所有源代码，或者基于本软件产品创作衍生作品；
 * 3、禁止进行逆向工程。不得对本软件的源代码进行逆向工程、反编译或试图以其他方式发现软件的源代码；
 * 4、个别授权：如需进行商业性的销售、复制、分发，包括但不限于软件销售、预装、捆绑等，必须获得知启蒙的书面授权和许可；
 * 5、保留权利：本注释未明示授权的其他一切权利仍归知启蒙所有，任何人使用其他权利时必须获得知启蒙的书面同意。
 */
package net.redxyz.repost.manage.action.app;

import java.util.ArrayList;
import java.util.List;

import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.context.extend.StdSwitchAction;
import org.zhiqim.httpd.validate.ones.IsAlphaNumericLen;
import org.zhiqim.httpd.validate.ones.IsIntegerValue;
import org.zhiqim.httpd.validate.ones.IsLen;
import org.zhiqim.httpd.validate.ones.IsNotEmpty;
import org.zhiqim.kernel.util.Ids;
import org.zhiqim.kernel.util.Lists;
import org.zhiqim.kernel.util.Strings;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.orm.ORM;
import org.zhiqim.orm.dbo.Selector;
import org.zhiqim.orm.dbo.Updater;

import net.redxyz.open.api.OpenApiService;
import net.redxyz.top.dbo.sys.SysApp;

/**
 * 应用接入管理
 * 
 * @version v1.0.0 @author yangpeng 2019-4-2 新建与整理
 */
public class AppAction extends StdSwitchAction
{
    
    protected void validateId(HttpRequest request) throws Exception
    {
        request.addValidate(new IsNotEmpty("appKey", "请选择应用"));
    }
    
    protected void validateForm(HttpRequest request) throws Exception
    {
        request.addValidate(new IsNotEmpty("appKey", "请选择应用编码"));
        request.addValidate(new IsLen("appName", "应用名称不能为空且不能超过32个汉字", 1, 32));
        request.addValidate(new IsAlphaNumericLen("appSecret", "应用密钥为32位数字和字符组成", 32, 32));
        request.addValidate(new IsIntegerValue("appStatus", "状态不能为空", 0, 1));
    }
    
    protected void list(HttpRequest request) throws Exception
    {
        List<SysApp> appList = ORM.table().list(SysApp.class, new Selector().addMustNotEqual("appStatus", 3));
        
        request.setAttribute("list", appList);
    }
    
    protected void add(HttpRequest request) throws Exception
    {
        request.setResponsePrivateCache();
        request.setAttribute("appKey", Ids.longId13_4());
    }
    
    protected void insert(HttpRequest request) throws Exception
    {
        SysApp app = request.getParameter(SysApp.class);
        String appActivityCode = Strings.trim(app.getAppActivityCode());
        List<String> ls = new ArrayList<String>();
        if (appActivityCode != null)
        {
            String[] arr = appActivityCode.replaceAll("，", ",").split(",");
            for (String code : arr)
            {
                if (Validates.isNotEmptyBlank(code))
                    ls.add(code);
            }
        }
        app.setAppActivityCode(Lists.toString(ls));
        app.setLoginUserCode(Strings.trim(app.getLoginUserCode()));
        long appKey = Ids.longId13();// 重新分配appKey
        app.setAppKey(appKey);
        ORM.table().insert(app);
        
        // 初始化禁用API
        OpenApiService.doInitForbidApi(appKey);
    }
    
    protected void modify(HttpRequest request) throws Exception
    {
        request.setResponsePrivateCache();
        
        long appKey = request.getParameterLong("appKey");
        if (appKey == -1)
        {
            request.returnHistory("请选择一个应用");
            return;
        }
        
        SysApp app = ORM.table().item(SysApp.class, new Selector("appKey", appKey).addMustNotEqual("appStatus", 3));
        if (app == null)
        {
            request.returnHistory("无效应用ID");
            return;
        }
        request.setAttribute("app", app);
    }
    
    protected void update(HttpRequest request) throws Exception
    {
        SysApp app = request.getParameter(SysApp.class);
        
        if (ORM.table().item(SysApp.class, app.getAppKey()) == null)
        {
            request.returnHistory("该应用不存在，请重新选择");
            return;
        }
        
        String appActivityCode = Strings.trim(app.getAppActivityCode());
        List<String> ls = new ArrayList<String>();
        if (appActivityCode != null)
        {
            String[] arr = appActivityCode.replaceAll("，", ",").split(",");
            for (String code : arr)
            {
                if (Validates.isNotEmptyBlank(code))
                    ls.add(code);
            }
        }
        
        app.setAppActivityCode(Lists.toString(ls));
        app.setLoginUserCode(Strings.trim(app.getLoginUserCode()));
        ORM.table().replace(app);
    }
    
    protected void delete(HttpRequest request) throws Exception
    {
        long appKey = request.getParameterLong("appKey");
        
        ORM.table().update(SysApp.class, new Updater().addMust("appKey", appKey).addField("appStatus", 3));
    }
    
}
